// Copyright (c) 2022 by Duguang.IO Inc. All Rights Reserved.
// Author: Ethan Liu
// Date: 2022-06-04 09:59:37

package runtime

import (
	"io"
	"strings"

	"jianmu-worker-docker/engine"
)

// replacer 找到并替换敏感数据
type replacer struct {
	w io.WriteCloser
	r *strings.Replacer
}

// newReplacer 返回一个io.WriteCloser
func newReplacer(w io.WriteCloser, secrets []*engine.Secret) io.WriteCloser {
	var oldnew []string
	for _, secret := range secrets {
		v := secret.GetValue()
		if len(v) == 0 || !secret.IsMasked() {
			continue
		}

		for _, part := range strings.Split(v, "\n") {
			part = strings.TrimSpace(part)

			// 跳过空字符串或单字符
			if len(part) < 2 {
				continue
			}

			masked := "******"
			oldnew = append(oldnew, part)
			oldnew = append(oldnew, masked)
		}
	}
	if len(oldnew) == 0 {
		return w
	}
	return &replacer{
		w: w,
		r: strings.NewReplacer(oldnew...),
	}
}

// Write 写入前过滤并替换敏感数据
func (r *replacer) Write(p []byte) (n int, err error) {
	_, err = r.w.Write([]byte(r.r.Replace(string(p))))
	return len(p), err
}

// Close 关闭WriteCloser
func (r *replacer) Close() error {
	return r.w.Close()
}
